package site.yunnong.atvris.service.impl;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import site.yunnong.atvris.common.api.ResultCodeEnum;
import site.yunnong.atvris.common.exception.YunnongBusinessException;
import site.yunnong.atvris.common.utils.SqlUtils;
import site.yunnong.atvris.dao.domain.User;
import site.yunnong.atvris.dao.domain.UserExample;
import site.yunnong.atvris.dao.mapper.UserMapper;
import site.yunnong.atvris.service.UserService;
import site.yunnong.atvris.service.domain.UmsUserDetails;
import site.yunnong.atvris.common.dto.UserQueryParam;

import javax.annotation.Resource;
import java.util.List;

/**
 * 
 *
 * @author zhangjinghao
 * @email jhzhang9102@163.com
 * @date 2021-07-09 23:45:38
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public int countUserByUsername(String username) {
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUsernameEqualTo(username);
        return (int) userMapper.countByExample(userExample);
    }

    @Override
    public int countUserByNickname(String nickname) {
        UserExample userExample = new UserExample();
        userExample.createCriteria().andNicknameEqualTo(nickname);
        return (int) userMapper.countByExample(userExample);
    }

    @Override
    public User queryUserByUsername(String username) {
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUsernameEqualTo(username);
        List<User> userList = userMapper.selectByExample(userExample);
        if (CollectionUtils.isEmpty(userList)) {
            return null;
        }
        return userList.get(0);
    }

    @Override
    public User queryUserByNickname(String nickname) {
        UserExample userExample = new UserExample();
        userExample.createCriteria().andNicknameEqualTo(nickname);
        List<User> userList = userMapper.selectByExample(userExample);
        if (CollectionUtils.isEmpty(userList)) {
            return null;
        }
        return userList.get(0);
    }

    @Override
    public User queryByUuid(Long uuid) {
        UserExample example = new UserExample();
        example.createCriteria().andUuidEqualTo(uuid);
        List<User> userList = userMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(userList)) {
            return null;
        } else {
            return userList.get(0);
        }
    }

    @Override
    public List<User> queryPage(UserQueryParam param) {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        UserExample userExample = buildExample(param);

        if (CollectionUtils.isEmpty(userExample.getOredCriteria())
                || CollectionUtils.isEmpty(userExample.getOredCriteria().get(0).getCriteria())) {
            return Lists.newArrayList();
        }
        return userMapper.selectByExample(userExample);
    }

    private UserExample buildExample(UserQueryParam param) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        if (!StringUtils.isEmpty(param.getUsername())) {
            criteria.andUsernameEqualTo(param.getUsername());
        }
        if (!StringUtils.isEmpty(param.getNickname())) {
            criteria.andNicknameEqualTo(param.getNickname());
        }
        if (param.getStatus() != null) {
            criteria.andStatusEqualTo(param.getStatus());
        }
        if (!StringUtils.isEmpty(param.getJob())) {
            criteria.andJobEqualTo(param.getJob());
        }
        if (param.getGender() != null) {
            criteria.andGenderEqualTo(param.getGender());
        }
        if (param.getEducation() != null) {
            criteria.andEducationEqualTo(param.getEducation());
        }
        if (!StringUtils.isEmpty(param.getCity())) {
            criteria.andCityEqualTo(param.getCity());
        }
        // 排序
        String orderByClause = SqlUtils.generateOrderByClause(param.getSortBy(), param.getSortRule());
        userExample.setOrderByClause(orderByClause);
        return userExample;
    }

    @Override
    public int insert(User user) {
        if (user.getId() != null) {
            throw new YunnongBusinessException(ResultCodeEnum.ERROR_PARAM_ILLEGAL, "id需为空");
        }
        return userMapper.insertSelective(user);
    }

    @Override
    public int update(User user) {
        if (user.getId() == null) {
            throw new YunnongBusinessException(ResultCodeEnum.ERROR_PARAM_ILLEGAL, "id需不为空");
        }
        return userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public User getCurrentUser() {
        SecurityContext ctx = SecurityContextHolder.getContext();
        Authentication auth = ctx.getAuthentication();
        User user = ((UmsUserDetails) auth.getPrincipal()).getUser();
        if (user == null) {
            throw new YunnongBusinessException(ResultCodeEnum.ERROR_UNAUTHENTICATED);
        }
        return user;
    }

    @Override
    public void updateByExampleSelective(User newUser, UserExample userExample) {
        userMapper.updateByExampleSelective(newUser, userExample);
    }

}

